﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

namespace seo
{
    class GoogleTranslate
    {
        public static string GetPage(string posturl, string postData)
        {
            //postData = "langpair=en|zh-CN&text=a%0D%0Aa";
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
            byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

        public static string GetRequest(string urlP, string encode)
        {
            if (null == urlP) return null;
            string StrRetP = null;
            Stream dataStream = null;
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(urlP);
                myHttpWebRequest.Timeout = 10000; // 10 secs 
                HttpWebResponse Objresponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                //Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page 
                if (Objresponse.StatusDescription == "OK")
                {//HttpStatusCode.OK 
                    dataStream = Objresponse.GetResponseStream();
                    Encoding objE = String.IsNullOrEmpty(encode) ? Encoding.GetEncoding(0) : Encoding.GetEncoding(encode);
                    StreamReader r = new StreamReader(dataStream, objE);
                    StrRetP = r.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                StrRetP = e.Message;
            }
            finally
            {
                if (null != dataStream) dataStream.Close();
            }
            return StrRetP;
        }

        public static string GetMatchString(string text, string pattern, int point)
        {
            if (String.IsNullOrEmpty(text) || String.IsNullOrEmpty(pattern)) return String.Empty;
            Regex rx = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Match match = rx.Match(text);
            string word = "";
            if (match.Success) word = match.Groups[point].Value;
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<br>[^<>]*?</span>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@"<[^>]*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            word = regex1.Replace(word, String.Empty);
            word = word.Replace("<br>", "\n");
            word = regex2.Replace(word, String.Empty);
            word = HttpUtility.HtmlDecode(word);
            return word;
        }

        public static string Translate(string text, string from, string to)
        {
            string mess = text.Replace("&", "%26");
            mess = mess.Replace("\n", "\n\n");
            //mess = HttpUtility.UrlEncodeUnicode(mess);
            //mess = GetRequest("http://translate.google.com/translate_t?langpair=" + UrlEncode("zh-CN|en") + "&text=" + UrlEncode(mess), "GB2312");
            //Console.WriteLine(mess); 
            mess = GetPage("http://translate.google.com/translate_t", "langpair=" + from + "|" + to + "&text=" + mess);
            mess = GetMatchString(mess, @"(<span id=result_box.*?>)(.*?(((?'Open'<span[^>]*>).*?)+((?'-Open'</span>).*?)+)*(?(Open)(?!)))(</span>)", 2);
            return mess;
        }

        public static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }
            
            return (sb.ToString());
        }
    }
}
